<!--
 * @Description: 
 * @Author: mmzhang
 * @Date: 2022-04-06 10:49:37
 * @LastEditTime: 2023-02-28 12:18:51
-->
<template>
  <dt-modal-edit ref="edit" title="回款计划" @ok="onOk" :width="1200" :transfer="true">
    <ul class="flex money-total">
      <li v-for="(item,index) in costList" :key="index">
        <p class="money-num text-center">{{$tool.formatterMoney(payMsg[item.key])}}</p>
        <p class="money-text text-center">{{item.title}}</p>
      </li>
    </ul>
    <div style="margin:10px 0;" class="flex flex-vertical-center">
      <Icon type="ios-help-circle-outline" color="#D9001B" />
      <p style="margin-left:5px">回款计划存在审核中金额与已入账金额时，不支持修改、删除；</p>
    </div>
    <dt-grid ref="table" :columns="columns" :list="collList" :heightResize="true">
    </dt-grid>
    <div class="add-btn" @click="addBtnFun">+ 添加回款计划</div>
  </dt-modal-edit>
</template>
<script>
  import columnConfig from './adjust'
  import comMgr from '@/biz/sales/salesCommon'
  import bankApi from '@/biz/buildingManagement/bank'
  import dt from '@dt/dt'

  export default {
    props: ['contractId'],
    data() {
      return {
        payMsg: {},
        columns: [],
        collList: [],
        bankList: [],
        costList:[
          {
            key:'totalPrice',
            title:'签约总价(元)'
          },
          {
            key:'accumulateMoney',
            title:'累计到账房款(元)'
          },
          {
            key:'remainingMoney',
            title:'剩余未到账房款(元)'
          }
        ]
      }
    },
    methods: {
      getBankList() {
        return bankApi.GetBankList({ housesId: dt.buildInfo().housesId }).then((res) => {
          if (res) {
            this.bankList = []
            res.forEach(item => {
              let obj = {
                value: item.bankName+'-'+item.subBankName,
                key: item.bankId
              }
              this.bankList.push(obj)
            })
          }
        })
      },

      async show(payMsg) {
        await this.getBankList()
        this.getPayLog()
        this.$refs.edit.show()
        this.$refs.table.init(this)
      },
      onOk() {
        // 判断计划回款金额相加应该和签约总价一致
        let sum = this.collList.reduce(function(sum, ele) {
          return sum + Number(ele.contractMoney ? ele.contractMoney : 0)
        }, 0)

        if (sum != this.payMsg.totalPrice) {
          this.$Message.error('计划回款金额相加应该和签约总价一致')
          return false
        }

        // '-'转换成null
        for (let i in this.collList) {
          this.$tool.transformationNullSet(this.collList[i])
        }

        try {
          this.collList.forEach((ele, index) => {
            if (index == 0 && (ele.contractMoney === null || ele.contractMoney === '')) {
              this.$Message.error('首付款金额不能为空，请检查！')
              throw Error();
            }
            if (index > 0 && (ele.contractMoney == 0 || ele.contractMoney === null || ele
                .contractMoney === '')) {
              this.$Message.error('除首付款外计划回款金额不能等于0且不为空，请检查！')
              throw Error();
            }
            if ((ele.contractTime === null || ele.contractTime === '')) {
              this.$Message.error(ele.paybackPeriodValue + '计划回款日期不能为空，请检查！')
              throw Error();
            }
            if ((ele.receiptType == 3 || ele.receiptType == 4) && (ele.loanBankId ===
                null || ele.loanBankId == '')) {
              this.$Message.error('组合贷款、商业贷款必选贷款银行，请检查！')
              throw Error();
            }
          })
        } catch (e) {
          return false
        }

        let params = {
          contractId: this.contractId,
          plans: this.collList
        }
        comMgr
          .adjustRepayPlanFun(params)
          .then((res) => {
            if (res) {
              this.$emit('onSearch')
              this.$refs.edit.hide()
            } else {
              this.getPayLog()
              this.$Message.error('新增回款记录，请重新调整回款计划')
            }
          })
          .catch((res) => {
            this.$emit('onSearch')
            this.getPayLog()
          })
      },
      getPayLog() {
        let params = {
          contractId: this.contractId,
        }
        comMgr
          .getPaymentMsg(params)
          .then((res) => {
            if (res) {
              this.payMsg = { ...res }
              this.collList = this.payMsg.repaymentPlanDetailInfoList
              this.columns = columnConfig.options(this)
            } else {
              this.payMsg = {}
              this.collList = []
            }
          })
          .catch((res) => {
            this.payMsg = {}
            this.collList = []
          })
      },
      onDeleteFun(row) {
        this.$Modal.confirm({
          title: '删除',
          content: '确认删除此回款计划？',
          closable: true,
          onOk: () => {
            for (let i = this.collList.length - 1; i >= 0; i--) {
              if (this.collList[i]._XID == row._XID) {
                this.collList.splice(i, 1)
              }
            }
          },
          onCancel: () => {},
        })
      },
      addBtnFun() {
        let num = null
        let paybackPeriodNum = null
        if (this.collList.length) {
          if (this.collList[0].paybackPeriodValue == '首付款') {
            paybackPeriodNum = this.collList.length
            num = this.$tool.convertToChinese(this.collList.length)
          } else {
            paybackPeriodNum = this.collList.length + 1
            num = this.$tool.convertToChinese(this.collList.length + 1)
          }
        } else {
          paybackPeriodNum = 0
          num = 0
        }

        let obj = {
          paybackPeriodValue: num == 0 ? '首付款' : `${num}` + '期款',
          paybackPeriodNum: paybackPeriodNum,
          isCanOperate: true,
          receiptType: null,
          contractMoney: '0',
          contractTime: '',
          approvingMoney: '0',
          payBackMoney: '0',
          loanBankId: '',
          bankName: ''
        }
        this.collList.push(obj)
      }
    }
  }
</script>
<style lang="scss" scoped>
  .money-total {
    li {
      padding: 0 40px;
      border-right: 1px solid #dadada;
    }

    li:last-child {
      border: none;
    }

    .money-num {
      font-size: 26px;
      color: #000;
      font-weight: bold;
      line-height: 50px;
    }
  }

  .add-btn {
    height: 48px;
    border: 1px solid #e8eaec;
    border-top: 0;
    text-align: center;
    line-height: 48px;
    cursor: pointer;
  }
</style>